<template>
  <div class="login">
    <div class="login-card">
      <div class="login-card-l">
        <div class="name">湖南水利科技</div>
        <div class="xian"></div>
        <div class="content">
          提供一站式精细化科技业务纵隔管理服务,
          支持全过程科研项目管理与专项资金管理
        </div>
      </div>
      <div class="login-card-r">
        <div class="login-tabs">
          <div class="login-tab" :class="{'login-tabs-checked': tabsIndex === 0}" @click="tabsIndex = 0">账号密码登录</div>
          <div class="login-tab" :class="{'login-tabs-checked': tabsIndex === 1}" @click="tabsIndex = 1">验证码登录</div>
        </div>
        <el-form ref="loginRef" v-if="tabsIndex === 0" :model="loginForm" :rules="loginRules" class="login-form">
          <!--          <h3 class="title">若依后台管理系统</h3>-->
          <el-form-item prop="roleValue">
            <el-select
                v-model="loginForm.roleValue"
                placeholder="请选择用户角色"
                size="large"
            >
              <template #prefix>
                <svg-icon icon-class="peoples" class="el-input__icon input-icon"/>
              </template>
              <el-option label="推荐单位" :value="1" />
              <el-option label="申报单位" :value="2" />
              <el-option label="评审专家" :value="3" />
              <el-option label="管理单位" :value="4" />
            </el-select>
          </el-form-item>
          <el-form-item prop="username">
            <el-input
                v-model="loginForm.username"
                type="text"
                size="large"
                auto-complete="off"
                placeholder="账号"
            >
              <template #prefix>
                <svg-icon icon-class="user" class="el-input__icon input-icon"/>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
                v-model="loginForm.password"
                type="password"
                size="large"
                auto-complete="off"
                placeholder="密码"
                @keyup.enter="handleLogin"
            >
              <template #prefix>
                <svg-icon icon-class="password" class="el-input__icon input-icon"/>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="code" v-if="captchaEnabled">
            <el-input
                v-model="loginForm.code"
                size="large"
                auto-complete="off"
                placeholder="验证码"
                style="width: 63%"
                @keyup.enter="handleLogin"
            >
              <template #prefix>
                <svg-icon icon-class="validCode" class="el-input__icon input-icon"/>
              </template>
            </el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode" class="login-code-img"/>
            </div>
          </el-form-item>
          <!--          <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>-->

          <el-form-item style="width:100%;">
            <el-button
                :loading="loading"
                size="large"
                type="primary"
                style="width:100%; background:#05559b;"
                @click.prevent="handleLogin"
            >
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
            <div class="registered" v-if="register">
              还没有账号？
              <router-link class="link-type" :to="'/register'">立即注册</router-link>
            </div>
          </el-form-item>
        </el-form>
        <el-form ref="loginRef2" v-if="tabsIndex === 1" :model="loginForm2" :rules="loginRules2" class="login-form">
          <!--          <h3 class="title">若依后台管理系统</h3>-->
          <el-form-item prop="roleValue">
            <el-select
                v-model="loginForm2.roleValue"
                placeholder="请选择用户角色"
                size="large"
            >
              <template #prefix>
                <svg-icon icon-class="peoples" class="el-input__icon input-icon"/>
              </template>
              <el-option label="推荐单位" :value="1" />
              <el-option label="申报单位" :value="2" />
              <el-option label="评审专家" :value="3" />
              <el-option label="管理单位" :value="4" />
            </el-select>
          </el-form-item>
          <el-form-item prop="username">
            <el-input
                v-model="loginForm2.username"
                type="text"
                size="large"
                auto-complete="off"
                placeholder="手机号"
            >
              <template #prefix>
                <svg-icon icon-class="phone" class="el-input__icon input-icon"/>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="code">
            <el-input
                v-model="loginForm2.code"
                type="text"
                size="large"
                auto-complete="off"
                placeholder="验证码"
                @keyup.enter="handleLogin"
            >
              <template #prefix>
                <svg-icon icon-class="log" class="el-input__icon input-icon"/>
              </template>
              <template #append>
                <el-button @click="getCaptcha" :disabled="text === '获取验证码' ? false : true">{{ text }}</el-button>
              </template>
            </el-input>
          </el-form-item>
<!--          <el-form-item prop="code" v-if="captchaEnabled">-->
<!--            <el-input-->
<!--                v-model="loginForm.code"-->
<!--                size="large"-->
<!--                auto-complete="off"-->
<!--                placeholder="验证码"-->
<!--                style="width: 63%"-->
<!--                @keyup.enter="handleLogin"-->
<!--            >-->
<!--              <template #prefix>-->
<!--                <svg-icon icon-class="validCode" class="el-input__icon input-icon"/>-->
<!--              </template>-->
<!--            </el-input>-->
<!--            <div class="login-code">-->
<!--              <img :src="codeUrl" @click="getCode" class="login-code-img"/>-->
<!--            </div>-->
<!--          </el-form-item>-->
          <!--          <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>-->

          <el-form-item style="width:100%;">
            <el-button
                :loading="loading"
                size="large"
                type="primary"
                style="width:100%; background:#05559b;"
                @click.prevent="handleLogin"
            >
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
            <div class="registered" v-if="register">
              还没有账号？
              <router-link class="link-type" :to="'/register'">立即注册</router-link>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="footer"></div>
  </div>
</template>

<script setup>
import {getCodeImg, message, plogin} from "@/api/login";
import Cookies from "js-cookie";
import {encrypt, decrypt} from "@/utils/jsencrypt";
import useUserStore from '@/store/modules/user'
import { setToken } from '@/utils/auth'

const userStore = useUserStore()
const route = useRoute();
const router = useRouter();
const {proxy} = getCurrentInstance();
const tabsIndex = ref(0);

const loginForm = ref({
  username: "admin",
  password: "admin123",
  rememberMe: false,
  yes: false,
  roleValue: null,
  code: "",
  uuid: ""
});

const loginRules = {
  username: [{required: true, trigger: "blur", message: "请输入您的账号"}],
  password: [{required: true, trigger: "blur", message: "请输入您的密码"}],
  roleValue: [{required: true, trigger: "blur", message: "请选择您的角色"}],
  code: [{required: true, trigger: "change", message: "请输入验证码"}]
};

const loginForm2 = ref({
  username: "",
  roleValue: null,
  code: ""
});

const loginRules2 = {
  username: [{required: true, trigger: "blur", message: "请输入您的手机号"}],
  roleValue: [{required: true, trigger: "blur", message: "请选择您的角色"}],
  code: [{required: true, trigger: "change", message: "请输入验证码"}]
};

const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 注册开关
const register = ref(true);
const redirect = ref(undefined);

watch(route, (newRoute) => {
  redirect.value = newRoute.query && newRoute.query.redirect;
}, {immediate: true});

function handleLogin() {
  if (tabsIndex.value == 0) {
    proxy.$refs['loginRef'].validate(valid => {
      if (valid) {
        loading.value = true;
        // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
        if (loginForm.value.rememberMe) {
          Cookies.set("username", loginForm.value.username, {expires: 30});
          Cookies.set("password", encrypt(loginForm.value.password), {expires: 30});
          Cookies.set("rememberMe", loginForm.value.rememberMe, {expires: 30});
        } else {
          // 否则移除
          Cookies.remove("username");
          Cookies.remove("password");
          Cookies.remove("rememberMe");
        }
        console.log(loginForm.value)
        loginForm.value.roleValue = parseInt(loginForm.value.roleValue)
        // 调用action的登录方法
        userStore.login(loginForm.value).then(() => {
          const query = route.query;
          const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
            if (cur !== "redirect") {
              acc[cur] = query[cur];
            }
            return acc;
          }, {});
          router.push({path: redirect.value || "/", query: otherQueryParams});
        }).catch(() => {
          loading.value = false;
          // 重新获取验证码
          if (captchaEnabled.value) {
            getCode();
          }
        });
      }
    });
  } else if(tabsIndex.value == 1) {
    proxy.$refs['loginRef2'].validate(valid => {
      if (valid) {
        loading.value = true;
        // 获取验证码
        plogin(loginForm2.value).then(res => {
          // 获取验证码成功
          if (res.code == 200) {
            // 获取验证码成功
            proxy.$modal.msgSuccess(res.msg);
            setToken(res.token)
            userStore.token = res.token
            // 跳转登录页面
            const query = route.query;
            const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
              if (cur !== "redirect") {
                acc[cur] = query[cur];
              }
              return acc;
            }, {});
            router.push({path: redirect.value || "/", query: otherQueryParams});
          } else {
            // 获取验证码失败
            proxy.$modal.msgError(res.msg);
          }
          loading.value = false;
        }).catch((e) => {
          loading.value = false;
        })
      }
    });
  }
}

function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.value.uuid = res.uuid;
    }
  });
}

const text = ref("获取验证码");
const getCaptcha = async () => {
  proxy.$refs["loginRef2"].validateField('username', (valid) => {
    if (valid) {
      let n = 60;
      text.value = n + "秒钟重新获取";
      const timer = setInterval(() => {
        if (n === 0) {
          clearInterval(timer);
          text.value = "获取验证码";
        } else {
          n--;
          text.value = n + "秒钟重新获取";
        }
      }, 1000);
      message({phone: loginForm2.value.username, type: 'PC_PHONE_LOGIN'}).then(res => {
        proxy.$modal.msgSuccess(res.msg);
      })
    } else {
      proxy.$modal.msgError("请输入正确的手机号")
    }
  });

};

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  };
}

getCode();
getCookie();
</script>

<style lang='scss' scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/bg.jpg");
  background-size: cover;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0);
  }
  .footer {
    height: 70px;
    width: 100vw;
    position: absolute;
    bottom: 0;
    background: #033560;
  }
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-card {
  width: 830px;
  background: #05559b;
  display: flex;
  justify-content: space-between;
  border-radius: 6px;
  z-index: 999;

  .login-card-l {
    width: 380px;
    padding: 10px;
    box-sizing: border-box;
    color: white;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .name {
      font-size: 36px;
    }

    .xian {
      height: 1px;
      background: #fff;
      width: 300px;
      margin: 40px 0;
    }

    .content {
      padding: 0 30px;
    }
  }

  .login-card-r {
    border-radius: 6px;
    background: #ffffff;
    width: 450px;
    padding: 35px 35px 15px 35px;

    .login-tabs {
      width: 100%;
      display: flex;
      justify-content: space-around;
      margin-bottom: 30px;

      .login-tab {
        cursor: pointer;
      }
    }

    .login-tabs-checked {
      color: #05559b;
      border-bottom: 1px solid #05559b;
    }

    .login-form {
      .el-input {
        height: 40px;

        input {
          height: 40px;
        }
      }

      .input-icon {
        height: 39px;
        width: 14px;
        margin-left: 0;
      }

      .registered {
        width: 100%;
        display: flex;
        justify-content: center;
        margin-top: 20px;
      }
    }
    .login-form :deep(.el-select__wrapper) {
      padding: 2px 16px;
    }
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 40px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 40px;
  padding-left: 12px;
}
</style>
